package com.truyen.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class FTPUpload {
    //chay dong nay tromg cmd cua win : netsh advfirewall set global StatefulFTP disable
	//moi su dung dc ham nay
    FTPClient ftp = null;
     
    public FTPUpload(String host, String user, String pwd) throws Exception{
        ftp = new FTPClient();
        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        int reply;
        ftp.connect(host);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new Exception("Exception in connecting to FTP Server");
        }
        ftp.login(user, pwd);
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        ftp.setControlKeepAliveTimeout(3000);
    }
    
    public void uploadFile(String pathFolder, String fileName){
        try{
        	File f = new File(pathFolder+fileName);
        	InputStream input = new BufferedInputStream(new FileInputStream(f));
            this.ftp.storeFile(pathFolder+fileName, input);
        }catch(Exception e){
        	e.printStackTrace();
        }
    }
 
    public void makeDir(String pathName){
    	try {
    		this.ftp.makeDirectory(pathName);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
 
    
    public void disconnect(){
        if (this.ftp.isConnected()) {
            try {
                this.ftp.logout();
                this.ftp.disconnect();
            } catch (IOException f) {
                // do nothing as file is already saved to server
            }
        }
    }
//    public static void main(String[] args) throws Exception {
//        System.out.println("Start");
//        FTPUpload ftpUploader = new FTPUpload("ftp.journaldev.com", "ftpUser", "ftpPassword");
//        ftpUploader.uploadFile("D:\\Pankaj\\images\\MyImage.png", "image.png", "/wp-content/uploads/image2/");
//        ftpUploader.disconnect();
//        System.out.println("Done");
//    }
 
}